package demo

import (
	"errors"
	"gim-server/config"
	"gim-server/consts"
	"gim-server/errs"
	"gim-server/model"
	"gim-server/sdk"
	"gim-server/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

type UserLoginArgs struct {
	UID string `json:"uid"`
}

type UserLoginDto struct {
	Token    string `json:"token"`
	UID      string `json:"uid"`
	Nickname string `json:"nickname"`
	Avatar   string `json:"avatar"`
	Gender   int    `json:"gender"`
	RegStep  int    `json:"reg_step"`
}

func userLogin(ctx *gin.Context) {
	var (
		err  error
		args = new(UserLoginArgs)
	)
	if err = ctx.ShouldBindJSON(args); err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiParamsErr,
			Err:  err,
		})
		return
	}
	db := sdk.DB(ctx)
	user := new(model.TbUserDemo)
	err = db.First(user, "uid = ?", args.UID).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			//注册
			user.UID = args.UID
			user.RegStep = 1
			user.CreatedAt = time.Now().Unix()
			user.LastActive = time.Now().Unix()
			if err = db.Create(user).Error; err != nil {
				utils.ERR(ctx, &utils.ErrArgs{
					Code: errs.ApiDbErr,
					Err:  err,
				})
				return
			}
		} else {
			utils.ERR(ctx, &utils.ErrArgs{
				Code: errs.ApiSrvErr,
				Err:  err,
			})
			return
		}
	} else {
		user.LastActive = time.Now().Unix()
		db.Save(user)
	}

	token, err := utils.CreateToken(config.GetCfg().SignKey, map[string]interface{}{
		consts.UID:   args.UID,
		consts.AppID: ctx.Request.Header.Get(consts.AppID),
	})
	if err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiSrvErr,
			Err:  err,
		})
		return
	}
	utils.SUC(ctx, &UserLoginDto{
		Token:    token,
		RegStep:  user.RegStep,
		UID:      user.UID,
		Nickname: user.Nickname,
		Avatar:   user.Avatar,
		Gender:   user.Gender,
	})
}
